package com.zb.mobile.network.service.impl;

import cn.dev33.satoken.stp.SaLoginModel;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zb.constant.AccountConstant;
import com.zb.constant.RedisConstant;
import com.zb.entity.*;
import com.zb.enums.DeviceType;
import com.zb.exception.SMSException;
import com.zb.extend.NetworkEmpLevelRelationExtend;
import com.zb.extend.NetworkEmpRelationExtend;
import com.zb.mapper.ZjNetworkEmpLevelMapper;
import com.zb.mapper.ZjWorkOrderMapper;
import com.zb.mobile.*;
import com.zb.mobile.network.service.ConNetworkAccountMobileService;
import com.zb.redis.RedisNetworkLoginTokenUtil;
import com.zb.redis.RedisUtil;
import com.zb.result.PageUtil;
import com.zb.secure.BCryptUtil;
import com.zb.service.*;
import com.zb.stp.StpNetworkUtil;
import com.zb.util.MobileNetworkSmsUtil;
import com.zb.utils.TokenNetworkUtil;
import com.zb.utils.VerificUtil;
import com.zb.vo.LoginVo;
import com.zb.vo.NetworkInviteCodeSetVo;
import com.zb.vo.UserContactVo;
import com.zb.vo.UserPasswordVo;
import com.zb.yaml.EnDeSecret;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.security.auth.login.LoginException;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Author WEN
 * @Date 2023/11/17 0017
 **/
@Service
public class ConNetworkAccountMobileServiceImpl implements ConNetworkAccountMobileService {
    @Resource
    private ZjAccountService accountService;
    @Resource
    private ZjNetworkEmpService networkEmpService;
    @Resource
    private ZjNetworkEmpRelationService networkEmpRelationService;
    @Resource
    private ZjCustomerService customerService;
    @Resource
    private ZjNetworkService networkService;
    @Resource
    private ZjNetworkEmpAddressService networkEmpAddressService;
    @Resource
    private ZjNetworkEmpLevelRelationService networkEmpLevelRelationService;
    @Resource
    private ZjNetworkInviteCodeSetService networkInviteCodeSetService;
    @Resource
    private ZjWorkOrderService workOrderService;
    @Resource
    private ZjWorkOrderMapper workOrderMapper;
    @Resource
    private ZjNetworkEmpLevelMapper networkEmpLevelMapper;
    // 服务商注册账号
    @Override
    @Transactional
    public void register(NetworkRegisterAccountVo registerAccountVo) throws SMSException {
        NetworkInviteCodeVo inviteCodeVo = null;
        if (StringUtils.isNotBlank(registerAccountVo.getInviteCode())) {
            inviteCodeVo = MobileNetworkSmsUtil.checkInviteCode(registerAccountVo.getInviteCode());
        }
        // 校验验证码
        MobileNetworkSmsUtil.checkRegisterVerificCode(registerAccountVo.getPhone(), registerAccountVo.getCode());

        Assert.isFalse(accountService.existByPhone(registerAccountVo.getPhone()), "该手机号已被注册");

        ZjAccount account = new ZjAccount();
        account.setId(IdWorker.getId());
        account.setSalt(BCryptUtil.generatorSalt());
        account.setAccount("ZB_" + BCryptUtil.generatorSalt().substring(10, 20));
        account.setPhone(registerAccountVo.getPhone());
        account.setPassword(BCryptUtil.encryPassword(registerAccountVo.getPassword(), account.getSalt()));
        account.setName(registerAccountVo.getName());
        account.setNickname(registerAccountVo.getPhone().substring(6));
        account.setAvatar("");
        account.setStatus(0);
        accountService.save(account);

        Long networkEmpId = networkEmpService.saveNetworkManager(account.getId());
        if (null != inviteCodeVo) {
            networkEmpRelationService.saveNetworkManager(inviteCodeVo.getCustAccId(), inviteCodeVo.getNetworkId(), networkEmpId);
        }
    }

    // 服务商登录
    @Override
    public AccountLoginToken login(LoginVo loginVo) throws SMSException, LoginException {
        ZjAccount account = null;
        if (loginVo.getType() == 1) {
            Assert.isTrue(VerificUtil.phoneVerific(loginVo.getPhone()), "手机号格式输入错误");
            MobileNetworkSmsUtil.checkLoginVerificCode(loginVo.getPhone(), loginVo.getPassword());
            account = accountService.getPhone(loginVo.getPhone());
        }
        if (loginVo.getType() == 2) {
            account = accountService.getByPhoneOrAccount(loginVo.getPhone());
        }
        if (null == account) {
            Assert.isTrue(false, "手机号未注册");
        }
        if (loginVo.getType() == 2) {
            Assert.isTrue(Objects.equals(account.getPassword(), BCryptUtil.encryPassword(loginVo.getPassword(), account.getSalt())), "账号或密码错误");
        }
        if (account.getStatus() == 1) {
            Assert.isTrue(false, "账号已被冻结");
        }
        if (account.getStatus() == 2) {
            Assert.isTrue(false, "账号已被封禁");
        }
        if (StpNetworkUtil.isLogin(account.getId())) {
            String oldAccessToken = StpNetworkUtil.getTokenValueByLoginId(account.getId(), DeviceType.ORDER_MOBILE.name());
            StpNetworkUtil.logout(account.getId(), DeviceType.ORDER_MOBILE.name());
            // 删除旧的登录缓存信息
            RedisNetworkLoginTokenUtil.removeAllTokenByAccessToken(oldAccessToken);
            RedisNetworkLoginTokenUtil.removeLoginAccessToken(oldAccessToken);
        }
        // 登录
        StpNetworkUtil.login(account.getId(), new SaLoginModel()
                .setTimeout(AccountConstant.LOGIN_TOKEN_REMEMBERME_EXPIRE_TIME)
                .setDevice(DeviceType.NETWORK_MOBILE.name())
        );
        AccounLoginInfo accounLoginInfo = new AccounLoginInfo(account.getId(), account.getAccount(), account.getPhone(), account.getName(), DeviceType.NETWORK_MOBILE.name());

        accountService.updateLastLoginTime(account.getId());
        return TokenNetworkUtil.getLoginToken(accounLoginInfo);
    }

    // 服务商刷新登录token
    @Override
    public AccountLoginToken refreshToken(String refreshToken) throws LoginException {
        if (!RedisNetworkLoginTokenUtil.hasAccessTokenByRefreshToken(refreshToken)) {
            throw new LoginException("登录已过期，请重新登录！");
        }
        // 旧token
        String oldAccessToken = RedisNetworkLoginTokenUtil.getAccessTokenByRefreshToken(refreshToken);
        AccounLoginInfo admInfo = RedisNetworkLoginTokenUtil.getAccountLoginInfoByAccessToken(oldAccessToken);
        // 退出旧的登录
        StpNetworkUtil.logout(admInfo.getId(), admInfo.getDevice());

        StpNetworkUtil.login(admInfo.getId(),
                new SaLoginModel()
                        .setDevice(admInfo.getDevice()) // 登录设备
                        .setIsLastingCookie(admInfo.isRememberMe()) // 记住我
                        .setTimeout(AccountConstant.LOGIN_TOKEN_REMEMBERME_EXPIRE_TIME) // 七天有效期
        );
        // 删除旧的登录缓存信息
        RedisNetworkLoginTokenUtil.removeAllTokenByAccessToken(oldAccessToken);
        RedisNetworkLoginTokenUtil.removeLoginAccessToken(oldAccessToken);
        return TokenNetworkUtil.getLoginToken(admInfo);
    }

    // 修改登录页面的密码
    @Override
    public void logInRestPwd(UserPasswordVo userPasswordVo) throws SMSException {
        if (userPasswordVo.getType() == 1) {
            Assert.isTrue(StringUtils.isNotBlank(userPasswordVo.getCode()), "验证码不能为空");
            MobileNetworkSmsUtil.checkUpdateVerificCode(userPasswordVo.getPhone(), userPasswordVo.getCode());
        }
        if (userPasswordVo.getType() == 2) {
            Assert.isTrue(StringUtils.isNotBlank(userPasswordVo.getOldPassword()), "旧密码不能为空");
        }
        ZjAccount account = accountService.getPhone(userPasswordVo.getPhone());
        Assert.isTrue(null != account, "该手机号未注册");
        if (userPasswordVo.getType() == 2) {
            Assert.isTrue(Objects.equals(account.getPassword(), BCryptUtil.encryPassword(userPasswordVo.getOldPassword(), account.getSalt())), "旧密码错误");
        }
        ZjAccount newAccount = new ZjAccount();
        newAccount.setId(account.getId());
        newAccount.setSalt(BCryptUtil.generatorSalt());
        newAccount.setPassword(BCryptUtil.encryPassword(userPasswordVo.getNewPassword(), newAccount.getSalt()));
        accountService.updateById(newAccount);
    }

    // 修改密码
    @Override
    public void updatePwd(Long accountId, UserPasswordVo userPasswordVo) throws SMSException {
        if (userPasswordVo.getType() == 1) {
            Assert.isTrue(StringUtils.isNotBlank(userPasswordVo.getCode()), "验证码不能为空");
            MobileNetworkSmsUtil.checkUpdateVerificCode(userPasswordVo.getPhone(), userPasswordVo.getCode());
        }
        ZjAccount account = accountService.getById(accountId);
        if (userPasswordVo.getType() == 2) {
            Assert.isTrue(StringUtils.isNotBlank(userPasswordVo.getOldPassword()), "旧密码不能为空");
            Assert.isTrue(Objects.equals(account.getPassword(), BCryptUtil.encryPassword(userPasswordVo.getOldPassword(), account.getSalt())), "旧密码错误");
        }
        ZjAccount newAccount = new ZjAccount();
        newAccount.setId(account.getId());
        newAccount.setSalt(BCryptUtil.generatorSalt());
        newAccount.setPassword(BCryptUtil.encryPassword(userPasswordVo.getNewPassword(), newAccount.getSalt()));
        accountService.updateById(newAccount);
    }

    // 根据账号ID获取账号所属商家信息
    @Override
    public NetworkMobileEmpVo getByAccountId(AccounLoginInfo loginInfo) {
        ZjNetworkEmp networkEmp = networkEmpService.getByAccountId(loginInfo.getId());
        if (null == networkEmp) {
            networkEmp = new ZjNetworkEmp();
            networkEmp.setId(networkEmpService.saveNetworkManager(loginInfo.getId()));
        }
        loginInfo.setNetworkEmpId(networkEmp.getId());

        ZjAccount account = accountService.getById(loginInfo.getId());
        NetworkMobileEmpVo vo = new NetworkMobileEmpVo();
        vo.setName(account.getName());
        vo.setPhone(account.getPhone());

        List<NetworkMobileVo> networks = new ArrayList<>();
        List<NetworkEmpRelationExtend> relationExtendList = networkEmpRelationService.getByNetworkEmpId(networkEmp.getId());
        if (CollectionUtil.isNotEmpty(relationExtendList) && relationExtendList.stream().anyMatch(f -> f.getNetworkId() > 0)) {
            List<Long> custAccIds = relationExtendList.stream().map(NetworkEmpRelationExtend::getCustAccId).distinct().toList();
            QueryWrapper<ZjCustomer> customerQueryWrapper = new QueryWrapper<>();
            customerQueryWrapper.select("id", "abbrevia");
            customerQueryWrapper.in("id", custAccIds);
            List<ZjCustomer> customerList = customerService.list(customerQueryWrapper);
            networks.addAll(relationExtendList.stream().map(e -> {
                NetworkMobileVo networkMobileVo = new NetworkMobileVo(BCryptUtil.aesEncry(EnDeSecret.aesKey(), e.getNetworkId().toString()), e.getNetwork());
                networkMobileVo.setRoleType(e.getManager()? 1: e.getSuperManager()? 2 : 0);
                networkMobileVo.setCustomer(customerList.stream().filter(f -> Objects.equals(f.getId(), e.getCustAccId())).map(ZjCustomer::getAbbrevia).findFirst().orElse(""));

                String aes = UUID.randomUUID().toString();
                networkMobileVo.setNetworkCode(BCryptUtil.aesEncry(aes, e.getNetworkId().toString()));
                RedisUtil.setCache(RedisConstant.ENTERPRISE_NETWORK_CODE + networkMobileVo.getNetworkCode(), aes, 5 * 60);
                return networkMobileVo;
            }).toList());
        } else {
            networks.add(new NetworkMobileVo(BCryptUtil.aesEncry(EnDeSecret.aesKey(), account.getId().toString()), account.getName()));
        }
        vo.setNetworks(networks);
        return vo;
    }

    // 根据服务商编码选择服务商
    @Override
    public void getNetwork(AccounLoginInfo loginInfo, String networkCode) {
        if (StringUtils.isBlank(networkCode)) {
            loginInfo.setNetworkId(0L);
            loginInfo.setCustAccId(0L);
            loginInfo.setCustAccLogoCode("sys_logo");
            loginInfo.setCustAccAnnexCode("sys_image");
            loginInfo.setCustAccVideoCode("sys_video");
            return;
        }
        Assert.isTrue(RedisUtil.hasKey(RedisConstant.ENTERPRISE_NETWORK_CODE + networkCode), "服务商编码已过期，请重新获取！", null);
        String aesKey = (String) RedisUtil.getByKey(RedisConstant.ENTERPRISE_NETWORK_CODE + networkCode);
        Long networkId = Long.parseLong(BCryptUtil.aesDecry(aesKey, networkCode));
        if (networkId == 0) {
            return;
        }
        loginInfo.setNetworkId(networkId);

        QueryWrapper<ZjNetwork> networkQueryWrapper = new QueryWrapper<>();
        networkQueryWrapper.select("cust_acc_id");
        networkQueryWrapper.eq("id", networkId);
        ZjNetwork network = networkService.getOne(networkQueryWrapper);
        loginInfo.setCustAccId(network.getCustAccId());

        QueryWrapper<ZjCustomer> customerQueryWrapper = new QueryWrapper<>();
        customerQueryWrapper.select("logo_code", "annex_code", "video_code");
        customerQueryWrapper.eq("id", loginInfo.getCustAccId());
        ZjCustomer customer = customerService.getOne(customerQueryWrapper);
        loginInfo.setCustAccLogoCode(customer.getLogoCode());
        loginInfo.setCustAccAnnexCode(customer.getAnnexCode());
        loginInfo.setCustAccVideoCode(customer.getVideoCode());
    }

    // 获取当前登录账号信息
    @Override
    public Object getAccountInfo(AccounLoginInfo loginInfo) {
        ZjAccount account = accountService.getById(loginInfo.getId());

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("id", null == loginInfo? "" : loginInfo.getNetworkEmpId());
        resultMap.put("empAccountId", null == loginInfo? "" : loginInfo.getId());
        resultMap.put("phone", null == loginInfo? "" : account.getPhone());
        resultMap.put("account", null == loginInfo? "" : account.getAccount());
        resultMap.put("name", null == loginInfo? "" : account.getName());
        resultMap.put("nickname", null == loginInfo? "" : account.getNickname());
        resultMap.put("status", null == loginInfo? "" : account.getStatus());
        resultMap.put("lastLoginTime", null == loginInfo? "" : account.getLastLoginTime());
        resultMap.put("avatar", null == loginInfo? "" : account.getAvatar());
        resultMap.put("bindingWechat", false); // TODO 是否绑定微信

        String network = ""; // 服务商名称
        String customer = ""; // 商家名称
        Boolean superManager = false; // 超级管理员：false-否，true-是
        Boolean manager = false; // 网点负责人：false-否，true-是
        String networkEmplevel = "";// 工程师等级名称
        if (null != loginInfo) {
            if (null != loginInfo.getNetworkId() && loginInfo.getNetworkId() != 0) {
                ZjNetwork net = networkService.getById(loginInfo.getNetworkId());
                if (null != net) network = net.getName();
            }
            if (null != loginInfo.getNetworkEmpId() && loginInfo.getNetworkEmpId() > 0) {
                // 查询工程师信息
                ZjNetworkEmp networkEmp = networkEmpService.getByAccountId(loginInfo.getId());
                if (networkEmp != null) {
                    List<Long> netWorkEmpIds = new ArrayList<>();
                    netWorkEmpIds.add(loginInfo.getNetworkEmpId());
                    //获取工程师的完成工单数
                    Map<Long, Long> orderCountMap = netWorkEmpIds.stream()
                            .collect(Collectors.toMap(
                                    empId -> empId,
                                    empId -> workOrderMapper.getNetworkMobileFinishOrderQty(loginInfo.getCustAccId(), loginInfo.getNetworkId(), loginInfo.getNetworkEmpId(), new NetworkOrderStatSelectVo())
                            ));
                    // 获取工程师等级
                    List<NetworkEmpLevelRelationExtend> byNetworkEmpLevel = networkEmpLevelRelationService.getByNetworkEmpIds(loginInfo.getCustAccId(), netWorkEmpIds);
                    Map<Long, NetworkEmpLevelRelationExtend> existingLevelMap = byNetworkEmpLevel.stream()
                            .collect(Collectors.toMap(
                                    NetworkEmpLevelRelationExtend::getNetworkEmpId,
                                    Function.identity()
                            ));
                    //计算并设置工程师等级
                    networkEmplevel = netWorkEmpIds.stream()
                            .map(empId -> {
                                // 获取完成工单数
                                Long orderCount = orderCountMap.getOrDefault(empId, 0L);

                                // 获取等级是否被修改
                                NetworkEmpLevelRelationExtend levelManualInfo = existingLevelMap.get(empId);

                                // 如果存在等级信息且是手动调整的，直接返回数据库中的等级
                                if (levelManualInfo != null && Boolean.TRUE.equals(levelManualInfo.getManualLevel())) {
                                    return levelManualInfo.getNetworkLevel();
                                }
                                // 根据完成工单数计算等级
                                if (orderCount >= 800) {
                                    return "金牌师傅";
                                } else if (orderCount >= 300) {
                                    return "银牌师傅";
                                } else if (orderCount >= 1) {
                                    return "铜牌师傅";
                                } else {
                                    return "普通师傅";
                                }
                            })
                            .findFirst()
                            .orElse("普通师傅");
//                    String substring = networkEmplevel.substring(0, 2);
                    QueryWrapper<ZjNetworkEmpLevel> wrapper = new QueryWrapper<>();
                    wrapper.select("id")
                            .eq("name", networkEmplevel).eq("cust_acc_id", loginInfo.getCustAccId());
                    ZjNetworkEmpLevel empLevelNameId = networkEmpLevelMapper.selectOne(wrapper);
                    if (empLevelNameId != null) {
                        // 获取当前等级ID
                        Long empLevelId = empLevelNameId.getId();
                        // 获取原来等级信息
                        NetworkEmpLevelRelationExtend levelInfo = existingLevelMap.get(loginInfo.getNetworkEmpId());
                        //更新等级信息
                        if (levelInfo != null && levelInfo.getNetworkLevel() != null) {
                            if (!existingLevelMap.containsKey(loginInfo.getNetworkEmpId()) || !levelInfo.getNetworkLevel().equals(networkEmplevel)) {
                                networkEmpLevelRelationService.save(loginInfo.getCustAccId(), loginInfo.getNetworkEmpId(), empLevelId);
                            }
                        }
                    }
                } else {
                    networkEmplevel = "普通师傅";
                }
                ZjNetworkEmpRelation empRelation = networkEmpRelationService.getNetworkEmpIdAndNetworkId(loginInfo.getNetworkEmpId(), loginInfo.getNetworkId());
                if (null != empRelation) {
                    superManager = empRelation.getSuperManager();
                    manager = empRelation.getManager();
                }
            }
            if (null != loginInfo.getCustAccId() && loginInfo.getCustAccId() > 0) {
                ZjCustomer zjCustomer = customerService.getById(loginInfo.getCustAccId());
                if (null != zjCustomer) customer = zjCustomer.getAbbrevia();
            }
        }
        resultMap.put("networkEmplevel", networkEmplevel);
        resultMap.put("network", network);
        resultMap.put("customer", customer);
        resultMap.put("roleType", manager? 1 : superManager? 2 : 0);
        // 新增服务商信息
        NetworkInviteCodeSetVo codeSet = networkInviteCodeSetService.getNetworkInviteCodeSet(loginInfo.getCustAccId());
        resultMap.put("inviteCode", codeSet.getInviteCode());
        return PageUtil.row(resultMap);
    }

    // 检查是否已绑定手机号
    @Override
    public Object checkBindingPhone(Long accountId) {
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("bindingPhone", false); // TODO 是否绑定手机号
        return resultMap;
    }

    // 编辑个人资料
    @Override
    public void updateNetworkEmpInfo(Long accountId, UserMobileInfoVo infoVo) {
        ZjAccount account = new ZjAccount();
        account.setId(accountId);
        account.setName(infoVo.getName());
        account.setNickname(infoVo.getNickname());
        account.setAvatar(infoVo.getAvatar());
        accountService.updateById(account);
    }

    // 绑定或换绑手机号
    @Override
    public void bindingPhone(Long accountId, String phone, String code) throws SMSException {
        ZjAccount account = accountService.getById(accountId);
        MobileNetworkSmsUtil.checkUpdateVerificCode(account.getPhone(), code);

        ZjAccount newAccont = new ZjAccount();
        newAccont.setId(accountId);
        newAccont.setPhone(phone);
        accountService.updateById(newAccont);
    }

    // 新增或修改服务人员地址
    @Override
    @Transactional
    public void saveNetworkEmpaddress(AccounLoginInfo loginInfo, UserContactVo networkEmpaddress) {
        ZjNetworkEmpAddress empAddress = networkEmpAddressService.getDefaultAddressByNetworkEmpId(loginInfo.getNetworkEmpId());
        if (null != empAddress && !networkEmpaddress.getMainContact() && Objects.equals(empAddress.getId(), networkEmpaddress.getId())) {
            Assert.isTrue(false, "当前地址为默认地址，取消当前默认地址前必须先指定一个默认的地址");
        }
        List<ZjNetworkEmpAddress> updates = new ArrayList<>();
        ZjNetworkEmpAddress address = new ZjNetworkEmpAddress();
        BeanUtil.copyProperties(networkEmpaddress, address);
        address.setName(networkEmpaddress.getUsername());
        address.setDefaultAddress(networkEmpaddress.getMainContact());
        if (null != empAddress && networkEmpaddress.getMainContact()) {
            if (!Objects.equals(empAddress.getId(), networkEmpaddress.getId())) {
                ZjNetworkEmpAddress empDefaultAddress = new ZjNetworkEmpAddress();
                empDefaultAddress.setId(empAddress.getId());
                empDefaultAddress.setDefaultAddress(false);
                updates.add(empDefaultAddress);
            }
        }
        if (null != address.getId()) {
            updates.add(address);
        } else {
            address.setId(IdWorker.getId());
            address.setNetworkEmpId(loginInfo.getNetworkEmpId());
            networkEmpAddressService.save(address);
        }
        if (CollectionUtil.isNotEmpty(updates)) networkEmpAddressService.updateBatchById(updates);
    }

    // 获取服务人员地址列表
    @Override
    public Map<String, Object> getNetworkEmpAddressList(Long networkEmpId, PageUtil pageUtil) {
        PageUtil.setPageLimitMobile(pageUtil);
        QueryWrapper<ZjNetworkEmpAddress> wrapper = new QueryWrapper<>();
        wrapper.select("id", "name", "phone", "province", "city", "area", "town", "address", "is_default_address AS defaultAddress");
        wrapper.eq("network_emp_id", networkEmpId);
        Page<ZjNetworkEmpAddress> page = networkEmpAddressService.page(new Page<>(pageUtil.getPage(), pageUtil.getLimit()), wrapper);
        return PageUtil.pageList(page.getCurrent(), page.getSize(), page.getTotal(), page.getRecords().stream().map(addr -> {
            UserContactVo vo = new UserContactVo();
            BeanUtil.copyProperties(addr, vo);
            vo.setUsername(addr.getName());
            vo.setMainContact(addr.getDefaultAddress());
            return vo;
        }).toList());
    }

    // 根据地址ID获取地址信息
    @Override
    public UserContactVo getNetworkEmpAddressDetail(Long networkEmpAddressId) {
        ZjNetworkEmpAddress empAddress = networkEmpAddressService.getById(networkEmpAddressId);
        Assert.isTrue(null != empAddress, "该服务人员地址信息不存在");
        UserContactVo vo = new UserContactVo();
        BeanUtil.copyProperties(empAddress, vo);
        vo.setUsername(empAddress.getName());
        vo.setMainContact(empAddress.getDefaultAddress());
        return vo;
    }

    // 根据地址ID删除地址信息
    @Override
    public void deleteNetworkEmpAddress(Long networkEmpAddressId) {
        ZjNetworkEmpAddress address = networkEmpAddressService.getById(networkEmpAddressId);
        Assert.isTrue(null != address && !address.getDefaultAddress(), "当前地址为默认地址，不允许删除");
        networkEmpAddressService.removeById(networkEmpAddressId);
    }

    // 注销账号
    @Override
    public void cancelAccount(AccounLoginInfo loginInfo) {
        List<NetworkEmpRelationExtend> extendList = networkEmpRelationService.getByNetworkEmpId(loginInfo.getNetworkEmpId());
        List<ZjNetworkEmpRelation> updateNetworkEmpRelationList = new ArrayList<>();
        ZjNetworkEmpRelation networkEmpRelation = null;
        if (null != loginInfo.getNetworkId() && loginInfo.getNetworkId() > 0) {
            networkEmpRelation = extendList.stream().filter(f -> Objects.equals(f.getNetworkId(), loginInfo.getNetworkId())).findFirst().orElse(null);
            if (null != networkEmpRelation) {
                networkEmpRelation.setQuit(true); // 离职相当于注销关联网点的账号
                updateNetworkEmpRelationList.add(networkEmpRelation);
            }
        } else {
            for (NetworkEmpRelationExtend extend : extendList) {
                networkEmpRelation = new ZjNetworkEmpRelation();
                networkEmpRelation.setId(extend.getId());
                networkEmpRelation.setQuit(true); // 离职相当于注销关联网点的账号
                updateNetworkEmpRelationList.add(networkEmpRelation);
            }
        }
        networkEmpRelationService.updateBatchById(updateNetworkEmpRelationList);
    }
}
